//获取应用实例
const app = getApp();
var url = getApp().globalData.ApiUrl;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bannerUrl: '/images/detail-bannaer.png', //banner图片
    goods: [],   // 商品列表
    active_id: 0,   // 营销活动id
    detailData: '', //商品详情具体数据
    goods_storage: '',  //商品库存
    goods_price: '', //商品价格
    specALLArr: [],  //商品规格名称
    goods_list: [],
    propertyChildNames: '', //已选中的商品
    buyGoods_id: '', //购物车要传的商品id
    showView: false,
    num: 1,
    disabled: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中，请稍后...',
    })
    // 获取新用户专场商品列表
    var key = wx.getStorageSync("key");
    wx.request({
      url: url + '/mobile/index.php?act=member_index&op=check_if_newbie',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      method: "POST",
      dataType: "json",
      data: {
        key: key,
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.hideLoading();
          if (res.data.datas.msg) {
            this.setData({
              disabled: true
            })
          } else {
            this.setData({
              disabled: false
            })
          }
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
          return false;
        }
      }
    })

    // 获取新人专场的商品列表
    wx.request({
      url: url + '/mobile/index.php?act=marketing_activity&op=get_activity_goods',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        activity_id: options.adv_url
      },
      success: (res) => {
        if (res.data.code == 200) {
          var arr = [];
          for (var i in res.data.goods_list) {
            arr.push(res.data.goods_list[i])
          }
          this.setData({
            goods: arr,
            banner_img: res.data.datas.marketing_activity_banner_all
          })
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            if (res.data.login == 0 && res.data.login) {
              wx.navigateTo({
                url: '/pages/authorize/index',
              })
            } else {
              wx.showToast({
                title: res.data.datas.error,
                icon: 'none',
                duration: 1500,
                mask: true
              })
            };
          };
        }
      },
      fail: ()=> {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  toDetailsTap: function(e) {
    var goods_id = e.currentTarget.dataset.goods_id;
    wx.navigateTo({
      url: '/pages/group-detail/index?goods_id=' + goods_id,
    })
  },
  // 加入购物车
  // 加入购物车--展开弹窗
  addToCar: function (e) {
    var that = this;
    var dataset = e.currentTarget.dataset;
    var mobile = wx.getStorageSync("mobile");
    if (!mobile) {
      wx.navigateTo({
        url: '/pages/phone/index',
      })
    };
    this.setData({
      goods_img: dataset.goods_img
    })
    that.getDetails(dataset);
  },
  /**
   * 获取商品详情
   */
  getDetails: function (dataset) {
    var that = this;
    wx.request({
      url: url + '/mobile/index.php?act=goods&op=goods_detail',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        goods_id: dataset.goods_id
      },
      success: (res) => {
        if (res.data.code == 200) {
          var datas = res.data.datas;
          var specObj = res.data.datas.goods_info.spec_name;
          var tmp = {}; //商品规格
          var tmp2 = {}; //商品尺寸
          var specALLArr = []; // 商品贵和和商品
          var goods_spec = [];
          var spec_id = [];
          for (var spec_d in res.data.datas.goods_info.goods_spec) {
            goods_spec.push(res.data.datas.goods_info.goods_spec[spec_d]);  // 商品规格
            spec_id.push(spec_d);
            var spec = goods_spec.toString().replace(/,/g, " ");
          };
          for (var i in specObj) {
            tmp.id = i;
            tmp.name = specObj[i];
            tmp.twoData = [];
            for (var j in res.data.datas.goods_info.spec_value[i]) {
              tmp2.id = j;
              tmp2.name = res.data.datas.goods_info.spec_value[i][j];
              tmp2.propertyID = i;
              tmp2.active = (j in res.data.datas.goods_info.goods_spec) ? true : false;
              tmp.twoData.push(JSON.parse(JSON.stringify(tmp2)));
            }
            specALLArr.push(JSON.parse(JSON.stringify(tmp)));
          };
          that.setData({
            specALLArr: specALLArr,
            detailData: datas,  //商品详情
            buyGoods_id: dataset.goods_id, //购买的商品价格
            goods_price: dataset.goods_price, //商品价格
            goods_storage: datas.goods_info.goods_storage, //商品库存
            showView: true
          });
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: ()=> {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000,
        })
      }
    });
  },
  /**
   * 加入购物车--提交购买
   * @author chelfinn
   * @date 2018-09-19
   */

  addInCar: function (e) {
    var that = this;
    var name = this.data.propertyChildNames.split(" ");
    if (this.data.specALLArr.length == 0) {
      if (this.data.goods_storage == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他商品~',
          showCancel: false
        });
        return false;
      };
    } else {
      if (this.data.goods_storage == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他商品~',
          showCancel: false
        });
        return false;
      };
      if (name.length != this.data.specALLArr.length) {
        wx.showModal({
          title: '提示',
          content: '请先选择商品规格和尺寸~',
          showCancel: false,
        });
        return false;
      }
    }
    wx.request({
      url: url + '/mobile/index.php?act=member_cart&op=cart_add',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'POST',
      data: {
        key: wx.getStorageSync('key'),
        goods_id: e.currentTarget.dataset.goods_id,
        quantity: e.currentTarget.dataset.quantity
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 2000
          });
          this.setData({
            showView: false,
            propertyChildNames: '',
          });
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
          this.setData({
            showView: false,
            propertyChildNames: '',
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000,
        })
      }
    });
  },
  errorTap: function () {
    this.setData({
      showView: false,
      propertyChildNames: '',
    });
  },
  // 减少商品数量
  minuAcvive: function() {
    var num = this.data.num;
    if (num == 1) {    //如果num大于1才能减
      num = 1;
    } else {
      num--;
    }
    this.setData({
      num:num
    })
  },
  // 增加数量
  addActive: function () {
    var num = this.data.num;
    num++;
    this.setData({
      num: num
    })
  }
})